package com.glm.fruit.controller;



import com.glm.fruit.dto.CartItemDto;
import com.glm.fruit.dto.CartRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/cart")
public class CartController {

    @PostMapping("/checkout")
    public Map<String, Object> checkout(@RequestBody CartRequest request) {
        double total = calculateTotal(request);
        Map<String, Object> result = new HashMap<>();
        result.put("total", String.format("%.2f", total));
        return result;
    }

    private double calculateTotal(CartRequest request) {
        double sum = 0;
        boolean strawberryDiscount = (request.getOption() == 3 || request.getOption() == 4);
        boolean fullReduction = (request.getOption() == 4);

        for (CartItemDto item : request.getItems()) {
            if ("草莓".equals(item.getName()) && strawberryDiscount) {
                sum += item.getPrice() * item.getWeight() * 0.8;
            } else {
                sum += item.getPrice() * item.getWeight();
            }
        }
        if (fullReduction && sum >= 100) {
            sum -= 10;
        }
        return sum;
    }
}